// pages/movies/more-movie/more-movie.js
var app = getApp()
var util = require('../../../utils/util.js')
Page({

  /**
   * 页面的初始数据
   */
  data: {
    movies: [],
    category: "",
    totalCount: 0,
    requestUrl: ""
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    let category = options.category
    this.data.category = category
    let dataUrl = ""
    switch (category) {
      case "正在热映":
        dataUrl = app.globalData.doubanBase + "/v2/movie/in_theaters"
        break
      case "即将上映":
        dataUrl = app.globalData.doubanBase + "/v2/movie/coming_soon"
        break
      case "豆瓣Top250":
        dataUrl = app.globalData.doubanBase + "/v2/movie/top250"
        break
    }
    this.data.requestUrl = dataUrl
    util.http(dataUrl, this.processDoubanData)
  },

  processDoubanData(moviesDouban) {
    for (let idx in moviesDouban.subjects) {
      let subject = moviesDouban.subjects[idx]
      let title = subject.title
      if (title.length >= 6) {
        title = title.substring(0, 6) + "..."
      }
      let temp = {
        stars: util.convertToStarsArray(subject.rating.stars),
        title,
        average: subject.rating.average,
        coverageUrl: subject.images.large,
        movieId: subject.id
      }
      this.data.movies.push(temp)
    }
    this.data.totalCount += 20
    this.setData({
      movies: this.data.movies
    })
    wx.hideNavigationBarLoading({
      complete: (res) => {console.log('加载完毕')},
    })
    wx.stopPullDownRefresh({
      complete: (res) => {console.log('下拉刷新完毕')},
    })
  },

  onScrollLower (event) {
    let nextUrl = this.data.requestUrl + "?start=" + this.data.totalCount + "&count=20"
    util.http(nextUrl, this.processDoubanData)
    wx.showNavigationBarLoading({
      complete: (res) => {console.log('加载开始')},
    })
  },
  onPullDownRefresh (event) {
    let refreshUrl = this.data.requestUrl + "?start=0&count=20"
    this.data.movies = []
    util.http(refreshUrl, this.processDoubanData)
    wx.showNavigationBarLoading({
      complete: (res) => {console.log('加载开始')},
    })
  },
  onMovieTap (event) {
    let movieId = event.currentTarget.dataset.movieId
    wx.navigateTo({
      url: '../movie-detail/movie-detail?movieId=' + movieId
    })
  },
  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {
    //wx.setxxxx()也会刷新页面
    wx.setNavigationBarTitle({
      title: this.data.category
    })
  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {

  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {

  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function () {

  }
})